/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.infodb.toolkit.annotation;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.*;

/**
 * @project-name:infodb
 * @package-name:com.hyts.infodb.toolkit.annotation
 * @author:LiBo/Alex
 * @create-date:2020-03-05 9:41
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description: 自定义注解操作解析器
 */
@NoArgsConstructor
@Slf4j
@Component
public class CustomAnnotationBeanProcessor {

    /**
     * spring 容器得操作解析器 专门根据指定得路径解析器
     */
    private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

    /**
     * 扫描得注解得操作包范围
     */
    private List<String> annotatedPackages = Lists.newArrayList();

    /**
     * 类型过滤器操作-专门定义注解得过滤器
     */
    private List<TypeFilter> typeFilters = Lists.newArrayList();

    /**
     * 注解操作类
     */
    private Set<Class<?>> annotatedClasses = Sets.newHashSet();

    /**
     * 操作模型控制处理
     */
    private static String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "%s/**/*.class";


    /**
     * @param packagesToScan 扫描得包范围 : 指定要扫描的包,支持多个包"package.a,package.b"并对每个包都会递归搜索
     * @param annotation 类型注解解析器  指定要扫描的注解
     */
    public CustomAnnotationBeanProcessor(String[] packagesToScan,
                                         Class<? extends Annotation>... annotation){
        if (packagesToScan != null) {
            for (String packagePath : packagesToScan) {
                this.annotatedPackages.add(packagePath);
            }
        }
        if (annotation != null) {
            for (Class<? extends Annotation> annotationElement : annotation) {
                typeFilters.add(new AnnotationTypeFilter(annotationElement, false));
            }
        }
    }

    /**
     * @param packagesToScan 扫描得包范围 : 指定要扫描的包,支持多个包"package.a,package.b"并对每个包都会递归搜索
     * @param annotations 类型注解解析器  指定要扫描的注解
     */
    public CustomAnnotationBeanProcessor(List<String> packagesToScan,
                                         List<Class<?>> annotations){
        if (packagesToScan != null) {
            for (String packagePath : packagesToScan) {
                this.annotatedPackages.add(packagePath);
            }
        }
        if (annotations != null) {
            for (Class annotationElement : annotations) {
                typeFilters.add(new AnnotationTypeFilter(annotationElement, false));
            }
        }
    }

    /**
     * @param packagesToScan 扫描得包范围 : 指定要扫描的包,支持多个包"package.a,package.b"并对每个包都会递归搜索
     * @param annotation 类型注解解析器  指定要扫描的注解
     */
    public CustomAnnotationBeanProcessor(String packagesToScan,
                                          Class<? extends Annotation>... annotation){
        if (Objects.nonNull(packagesToScan)) {
            this.annotatedPackages.add(packagesToScan);
        }
        if (annotation != null) {
            for (Class<? extends Annotation> annotationElement : annotation) {
                typeFilters.add(new AnnotationTypeFilter(annotationElement, false));
            }
        }
    }

    /**
     *
     * @param targetClass 指定类得包范围内
     * @param annotation 类型注解解析器  指定要扫描的注解
     */
    public CustomAnnotationBeanProcessor(Class targetClass,
                                         Class<? extends Annotation>... annotation){
        if (Objects.nonNull(targetClass)) {
            this.annotatedPackages.add(targetClass.getPackage().getName());
        }
        if (annotation != null) {
            for (Class<? extends Annotation> annotationElement : annotation) {
                typeFilters.add(new AnnotationTypeFilter(annotationElement, false));
            }
        }
    }

    /**
     * 获取所有得相关得class列表信息服务对象
     * @return
     */
    public Set<Class<?>> getAnnotatedClasses(){
        // 情况之前得所有服务对象类
        this.annotatedClasses.clear();
        // 扫描相关得注释包
        if(!CollectionUtils.isEmpty(this.annotatedPackages)){
            try {
                for(String packageName : this.annotatedPackages){
                    String patternPath = String.format(pattern, ClassUtils.convertClassNameToResourcePath(packageName));
                    Resource[] resources = this.resourcePatternResolver
                            .getResources(patternPath);
                    //元数据解析器工厂类
                    MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(
                            this.resourcePatternResolver);
                    // 获取得到多个资源类
                    for (Resource resource : resources) {
                        if (resource.isReadable()) {
                            MetadataReader reader = readerFactory
                                    .getMetadataReader(resource);
                            String className = reader.getClassMetadata()
                                    .getClassName();
                            if (matchesEntityTypeFilter(reader, readerFactory)) {
                                this.annotatedClasses.add(Class.forName(className));
                            }
                        }
                    }
                }
            } catch (IOException | ClassNotFoundException e) {
                log.error("操作扫描包失败",e);
            }
        }
        // 输出日志
        if (log.isInfoEnabled()) {
            for (Class<?> clazz : this.annotatedClasses) {
                log.info("Found class:{}",clazz.getName());
            }
        }
        return this.annotatedClasses;
    }

    /**
     * 检查当前扫描到的类是否包含指定的注解
     *
     * @param reader
     * @param readerFactory
     * @return
     * @throws IOException
     */
    private boolean matchesEntityTypeFilter(MetadataReader reader,
                                            MetadataReaderFactory readerFactory) throws IOException {
        if (!this.typeFilters.isEmpty()) {
            for (TypeFilter filter : this.typeFilters) {
                if (filter.match(reader, readerFactory)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
        List<Class<?>> annotations = new ArrayList<Class<?>>(){{add(Component.class);}};
        List<String> packageScans = new ArrayList<String>(){{add(CustomAnnotationBeanProcessor.class.getPackage().getName());}};
        CustomAnnotationBeanProcessor factory = new CustomAnnotationBeanProcessor(packageScans,annotations);
        System.out.println(factory.getAnnotatedClasses());
    }

}
